﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Castle.Core.Logging;

namespace Structura.Silverlight.Infrastructure.Logging
{
	public class BrowserConsoleAppender : IAppender
	{
      #region IAppender Members

		public void Log(LoggerLevel loggerLevel, string loggerName, string message, Exception exception)
		{
			HtmlWindow window = HtmlPage.Window;
			//only log is a console is available (IE and FF)
			var isConsoleAvailable = (bool)window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'");
			if (isConsoleAvailable)
			{
				var console = (window.Eval("console.log") as ScriptObject);
				if (console != null)
				{
					DateTime dateTime = DateTime.Now;
					string output;
					if (exception == null)
						output = string.Format("{0} [{1}] '{2}' {3}", dateTime.ToString("u"), loggerLevel, loggerName, message).SanitizeForBrowser();
					else
						output = string.Format("{0} [{1}] '{2}' {3}:\n{4}\n{5}", dateTime.ToString("u"), loggerLevel, loggerName, exception.GetType().FullName,
											 exception.Message, exception.StackTrace).SanitizeForBrowser();

					console.InvokeSelf(output);
				}
			}
		}

		#endregion
	}
}
